package com.yoyo.yyadsdk.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.ServiceManager;

import com.yoyo.yyadsdk.bean.UserActive;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class PackageUtil {

    private static final String TAG = "PackageUtil";

    static boolean isInUserActiveRules(Context context, List<UserActive> userActiveList, boolean isWhite) {
        if (userActiveList == null || userActiveList.size() == 0) {
            return isWhite;
        }
        if (Build.VERSION.SDK_INT < 21) {
            return isInUserActiveRulesOld(context, userActiveList, isWhite);
        } else {
            return isInUserActiveRulesNew(context, userActiveList, isWhite);
        }
    }

    @SuppressWarnings("ResourceType")
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static boolean isInUserActiveRulesNew(Context context, List<UserActive> userActiveList, boolean isWhite) {
        Calendar c = Calendar.getInstance(Locale.getDefault());
        c.setTime(new Date());
        long endTime = c.getTimeInMillis();
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) - 3);
        long startTime = c.getTimeInMillis();
        UsageStatsManager mUsmManager = (UsageStatsManager) context.getSystemService("usagestats");
        Map<String, UsageStats> map = mUsmManager.queryAndAggregateUsageStats(startTime, endTime);
        for (UserActive u : userActiveList)
            for (Map.Entry<String, UsageStats> entry : map.entrySet()) {
                UsageStats stats = entry.getValue();
                if (u.getPkgName().equals(stats.getPackageName()))
                    if (isWhite) {
                        if (stats.getTotalTimeInForeground() <= u.getTime() * TimeUtils.HOUR)
                            return true;
                    } else {
                        if (stats.getTotalTimeInForeground() > u.getTime() * TimeUtils.HOUR)
                            return true;
                    }
            }
        return false;
    }

    private static int getLaunchCount(UsageStats usageStats) {
        Field field;
        try {
            field = usageStats.getClass().getDeclaredField("mLaunchCount");
            return (int) field.get(usageStats);
        } catch (NoSuchFieldException e) {
            return 0;
        } catch (IllegalAccessException e) {
            return 0;
        }
    }

    /**
     * 是否在规则中
     */
    @SuppressLint("PrivateApi")
    private static boolean isInUserActiveRulesOld(Context context, List<UserActive> userActiveList, boolean isWhite) {
        if (userActiveList == null || userActiveList.size() == 0) {
            return false;
        }
        PackageManager manager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
        List<ComponentName> names = new ArrayList<>();
        for (ResolveInfo info : infos) {
            ComponentName cn = new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
            names.add(cn);
        }
        try {
            Class<?> cStub = Class.forName("com.android.internal.app.IUsageStats$Stub");
            Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
            Object mUsageStatsService = asInterface.invoke(null, ServiceManager.getService("usagestats"));
            Method getPkgUsageStats = mUsageStatsService.getClass().getMethod("getPkgUsageStats", ComponentName.class);
            for (UserActive u : userActiveList) {
                ComponentName name = getComponentName(names, u.getPkgName());
                if (name == null) {
                    continue;
                }
                Object state = getPkgUsageStats.invoke(mUsageStatsService, name);
                if (state != null) {
                    Class<?> PkgUsageStats = Class.forName("com.android.internal.os.PkgUsageStats");
                    long usageTime = PkgUsageStats.getDeclaredField("usageTime").getLong(state);
//                    int launchCount = PkgUsageStats.getDeclaredField("launchCount").getInt(state);
                    if (isWhite) {
                        if (usageTime <= u.getTime() * TimeUtils.HOUR)
                            return true;
                    } else {
                        if (usageTime > u.getTime() * TimeUtils.HOUR)
                            return true;
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static ComponentName getComponentName(List<ComponentName> infos, String name) {
        for (ComponentName info : infos)
            if (name.equals(info.getPackageName()))
                return info;
        return null;
    }
}
